<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item label="提箱单号">
        <el-input v-model.trim="param.packingNo" clearable  placeholder="请输入提箱单号"></el-input>
      </el-form-item>
      <el-form-item label="箱型">
        <el-select v-model="param.boxType" clearable style="width:100%" placeholder="选择箱型">
          <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="箱况">
        <el-select v-model="param.boxCondition" clearable style="width:100%" placeholder="选择箱况">
          <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="箱贸企业">
        <el-input v-model.trim="param.companyName" clearable placeholder="请输入箱贸企业"></el-input>
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model.trim="param.orderNo" clearable placeholder="请输入订单号"></el-input>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" @click="toExportBoxEastRentOrder" plain>导出</el-button>
    </span>
    <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有数据" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="selectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" @click="toExportListData" plain>导出</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" style="width: 100%;" :allId="allId" :isAllCheck="isAllCheck"
           @pageChange="onTablePageChange" @showInfo="showInfo"
           @downloadFile="downloadFile" @updateSelectAll="updateSelectAll" @activeAddPacking="activeAddPacking"
           @showPackingRecord="showPackingRecord" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 添加提箱记录 -->
    <el-drawer v-model="param.drawer1" :with-header="false">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>添加提箱记录
      </span>
      <el-form label-width="100px" style="margin-top: 20px;">
        <el-form-item label="提箱单号">{{ rowData.packingNo }}</el-form-item>
        <el-form-item label="堆场名称">
          <el-input v-model="param.yardName"></el-input>
        </el-form-item>
        <el-form-item label="箱型">{{ boxTypeFilter(rowData.boxType) }}</el-form-item>
        <el-form-item label="箱况">{{ boxConditionFilter(rowData.boxCondition) }}</el-form-item>
        <!-- <el-form-item label="司机信息">
          <el-input v-model="param.driverInfo"></el-input>
        </el-form-item> -->
        <el-form-item label="箱号">
          <boxSelect v-model="param.containerNo" :needInfo="true" :boxCondition="rowData.boxCondition"
                     :companyId="rowData.companyId" :boxType="rowData.boxType" :boxEastYardId="rowData.yardId"
                     @boxId="boxInfoData" style="width: 100%;">
          </boxSelect>
        </el-form-item>
        <el-form-item label="提箱日期">
          <el-date-picker v-model="param.packingDate" type="date" :default-value="new Date()"/>
        </el-form-item>
        <el-form-item label="提箱附件">
          <img-upload :type="'pdf_jpg_png_zip'" :limit="10" :multiple="true"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddPacking">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 提箱记录 -->
    <el-drawer v-model="param.drawer3" :with-header="false">
      <span class="_before">提箱记录</span>
      <div style="float: right;margin-top: 60px;">
        <span>应提箱量：{{ rowData.totalQuantity }} 个</span> &nbsp;
        <span>实提箱量：{{ rowData.packedQuantity }} 个</span>
      </div>
      <el-table :data="packingRecord" style="margin-top: 100px;">
        <el-table-column prop="containerNo" label="箱号" width="120px" align="center"/>
        <el-table-column prop="boxType" label="箱型" width="70px" align="center"/>
        <el-table-column prop="boxCondition" label="箱况" width="70px" align="center"/>
        <el-table-column prop="packingDate" label="提箱日期" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="companyName" label="卖家" align="center"/>
      </el-table>
    </el-drawer>

    <!-- info -->
    <el-dialog v-model="param.dialogVisibleInfo" :with-header="false" width="650">
      <span class="_before">提箱单详情</span>
      <el-row justify="center" align="middle" class="marginTop10 elRow-box">
        <el-col :offset="2" :span="18" class="marginTop10"><span>卖家:</span><span>{{
            param.boxInfo.companyName
          }}</span></el-col>
        <el-col :offset="2" :span="18" class="marginTop10"><span>提箱单号:</span><span>{{
            param.boxInfo.packingNo
          }}</span></el-col>
        <el-col :offset="2" :span="18" class="marginTop10"><span>购箱订单:</span>
          <div class="marginTop10">
            <el-table :data="param.boxInfo.tableOrder">
              <el-table-column prop="orderNo" label="订单号" width="200"></el-table-column>
              <el-table-column prop="planPickupDate" label="预计提箱日期" width="150">
                <template #default="scope">
                  {{ formatDate(scope.row.planPickupDate, 2) }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="下单日期">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime, 2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <!-- <el-col :offset="2" :span="18" class="marginTop10"><span>提箱单有效期范围:</span><span>{{ param.boxInfo.packingNo }}</span></el-col> -->
        <el-col :offset="2" :span="18" class="marginTop10"><span>箱型/箱况/箱量:</span>
          <div class="marginTop10">
            <el-table :data="param.boxInfo.tableBox">
              <el-table-column prop="boxType" label="箱型"></el-table-column>
              <el-table-column prop="totalQuantity" label="箱量"></el-table-column>
              <el-table-column prop="boxCondition" label="箱况"></el-table-column>
            </el-table>
          </div>
        </el-col>
        <!-- <el-col :offset="2" :span="18" class="marginTop10"><span>提箱单附件:</span><span><showFile :detailFileList="param.boxInfo.packingFileList"></showFile></span></el-col> -->
        <el-col :offset="2" :span="18" class="marginTop10">
          <span>状态:</span><span>{{ param.statusFilter[param.boxInfo.status] }}</span></el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {formatDate} from '@/utils'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import {
  buyBoxPage,
  batchFinish,
  getPackingInfo,
  downloadStutas,
  exportBuyBoxPackingList
} from '@/api/boxDeal/tiXiangManage';
import {addPackingDetail, buyBoxPage as getDetailTable} from '@/api/boxDeal/tiXiangManageDetail';
import boxSelect from '@/components/citySelect/boxSelect.vue';
import {computed, onMounted, onActivated, reactive, ref} from 'vue';
import imgUpload from '@/components/upload/index.vue'
import {downloadIamge, downloadFile as downloadFileExcel} from '@/utils/download'
import {
  Plus,
  Delete,
  Edit,
  Message,
  Search,
  Download,
  Upload,
  Refresh,
  UploadFilled,
  Finished
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus';
import {saleBoxPage} from "../../../api/boxDeal/tiXiangManage.ts";
import {useRoute} from 'vue-router'

const param = reactive({
  value1: [],
  boxInfo: {code: '123456789', type: "40HQ", info: "无"},
  pageNum: 0,
  pageSize: 10,
  dialogTableVisible: false,
  drawer: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  statusFilter: {5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成'},

  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    {value: '5', label: '40HQ',},
    {value: '10', label: '40GP',},
    {value: '15', label: '20HQ',},
    {value: '20', label: '20GP',},
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    {value: '15', label: '适货',},
    {value: '10', label: '次新',},
    //{ value: '20', label: '混提(次新或者适货)', },
    {value: '5', label: '全新',},
  ],
  packingNo: '',
  companyName: ''
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    {key: 'packingNo', colWidth: '130', title: '提箱单号', type: '<a>', command: 'showInfo', isCheck: true},
    {key: 'orderList', key2: 'orderNo', colWidth: '130', title: '订单号', type: '/', isCheck: true},
    // { key: 'yardName', title: '堆场名称', type: 'text', isCheck: true },
    {
      key: 'boxType',
      colWidth: '60',
      title: '箱型',
      type: 'filter',
      filter: {5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP'},
      isCheck: true
    },
    {
      key: 'boxCondition',
      colWidth: '60',
      title: '箱况',
      type: 'filter',
      filter: {5: '全新', 10: '次新', 15: '适货'},
      isCheck: true
    },
    // { key: 'totalQuantity', colWidth: '60', title: '箱量', type: 'text', isCheck: true },
    // { key: '', title: '剩余提箱天数', type: 'text', isCheck: true },
    // { key: '', title: '提箱单有效期范围', type: 'text', isCheck: true },
    {key: 'totalQuantity', colWidth: '60', title: '总箱量', type: 'totalQuantity', isCheck: true},
    {key: 'packedQuantity', colWidth: '60', title: '已提箱量', type: 'totalQuantity', isCheck: true},
    {key: 'totalQuantity', key2: 'packedQuantity', colWidth: '60', title: '未提箱量', type: 'quantity', isCheck: true},
    {key: 'status', colWidth: '70', title: '状态', type: 'statusTixiang', isCheck: true},
    {key: 'companyName', title: '集装箱公司', colWidth: '180', type: 'text', isCheck: true},
    {key: 'boxEastOperatorUserName', colWidth: '70', title: '联系人', type: 'text', isCheck: true},
    {
      key: 'boxEastOperatorUserTel',
      colWidth: '140',
      title: '联系电话',
      type: 'phoneNumber',
      areaCode: "boxEastOperatorUserAreaCode",
      isCheck: true
    },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'Download',
          command: 'downloadFile',
          // content: '下载提箱单',
          name: '下载',
        },
        {
          // icon: 'ChatLineSquare',
          command: 'showPackingRecord', //param.drawer3
          // content: '提箱记录',
          name: '提箱记录'
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

const typeList = computed(() => {
  const list = [{id: 0, name: '全部'}, {id: 5, name: '已发放'}, {id: 10, name: '已下载'}, {
    id: 15,
    name: '提箱中'
  }, {id: 20, name: '已完成'}]
  return list
})
const route = useRoute();

onActivated(() => {
  if(route.query.refNo){
    param.packingNo=route.query.refNo
  }
  getTableData()
})

/*
# 买箱公司: 查询提箱单分页列表
# POST {{baseUrl}}/salePackingLists/buyBoxPage
# 过滤条件： 提箱单号:String packingNo   箱况:boxCondition   箱型:boxType
# 提箱单状态 5-已发放 10-已下载 15-提箱中 20-已完成  Integer status
# 卖箱公司Id:companyId  卖箱公司名称:companyName 
*/
const getTableData = () => {
  const data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderNo: param.orderNo?.toUpperCase(),
    // containerNo: param.containerNo,
    packingNo: param.packingNo?.toUpperCase(),
    boxType: param.boxType,
    boxCondition: param.boxCondition,
    status: param.status,
    companyName: param.companyName
  }
  buyBoxPage(data).then((res: any) => {
    table.data = res.data.list;
    table.config.total = res.data.total;
  })
}

function handleReset() {
  param.containerNo = null
  param.packingNo = null
  param.boxType = null
  param.boxCondition = null
  param.orderNo = null
  param.companyName = null
  getTableData()
}

function handleTypeChange(val: any) {
  // console.log(val)
  param.status = val
  getTableData()
}

// const handlePacking = () => {
//   param.drawerPacking = true
//   param.packingInfo = { orderType: 200 }
// };

const successPacking = () => {
  ElMessage.success('提箱单开具成功！')
  param.drawerPacking = false
}

//下载--------------- 
const downloadFile = (rowData: any) => {
  console.log("rowDatarowDatarowData", rowData)
  if (rowData.packingFileList) {
    const pdfFile = JSON.parse(rowData.packingFileList)
    if (pdfFile.length < 1 || !pdfFile[0].url) return ElMessage.error('chengzhi 未找到文件')
    downloadIamge(pdfFile[0].url,pdfFile[0].originalFileName || new Date(Date.now()+28800000).toISOString())
    downloadStutas(rowData.id) //更新下载状态
  } else {
    ElMessage.error('chengzhi 未找到文件')
  }
}
// const infoDownloadFile = (file: any) => {
//   if (file) {
//     if (!file.url) return ElMessage.error('chengzhi 未找到文件')
//     downloadIamge(file.url)
//   } else {
//     console.log(rowData)
//     ElMessage.error('chengzhi 未找到文件')
//   }
// }

// 添加提箱记录
const rowData = ref({})
const activeAddPacking = (row: any) => {
  rowData.value = row
  param.drawer1 = true
  // orderBoxQty(row.id).then((res: any) => {
  //   param.orderList = res.data
  //   res.data.forEach((item: any) => {
  //     item.waitPackingQuantity = item.totalQuantity - 0 - (item.packedQuantity - 0)
  //   })
  //   param.drawer1 = true
  // }).catch((err: any) => {
  //   ElMessage.error('查询订单失败！')
  // })
}
const handleAddPacking = () => {
  console.log("添加提箱记录")
  console.log(param.orderId)
  const data = {
    "packingId": rowData.value.id,
    "containerNo": param.containerNo,
    // "driverInfo": param.driverInfo,
    "packingDate": param.packingDate,
    "yardName": param.yardName,
    "detailFileList": "123"
  }
  addPackingDetail(data).then((res: any) => {
    getTableData()
    param.drawer1 = false
  })
}

//查看提箱记录
const packingRecord = ref([])
const showPackingRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
  const data = {
    pageNum: 1,
    pageSize: 200,
    packingId: row.id
  }
  getDetailTable(data).then((res: any) => {
    let list = res.data.list
    list.forEach((item: any) => {
      item.boxCondition = boxConditionFilter(item.boxCondition)
      item.boxType = boxTypeFilter(item.boxType)
    })
    packingRecord.value = list
  })
}

//提完
const tableRef = ref({multipleSelection: []})
const endPacking = (row: any) => {
  const selection = tableRef.value.multipleSelection
  if (selection.length == 0) {
    return ElMessage.warning('请选择操作行')
  }
  let packingNosStr = getPackingNosStr(selection)
  ElMessageBox.confirm('确定提箱单 ' + packingNosStr + ' 已提完吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchFinish(row.id).then((res: any) => {
      ElMessage.success(packingNosStr + '已提完')
    })
  }).catch(() => {
  });
}

const getPackingNosStr = (selection: any) => {
  let str = ''
  selection.forEach((item: any, index: number) => {
    let dos = index ? ' , ' : ''
    str += dos + item.packingNo
  })
  return str
}

//详情
const showInfo = (row: any) => {
  if (!row.id) {
    ElMessage.error('提箱单 id 为空')
  }
  getPackingInfo(row.id).then((res: any) => {
    let resp = res.data
    const orderList = JSON.parse(resp.orderList)
    param.boxInfo = resp
    param.boxInfo.tableOrder = orderList
    param.boxInfo.tableBox = [{
      boxType: boxTypeFilter(resp.boxType),
      totalQuantity: resp.totalQuantity,
      boxCondition: boxConditionFilter(resp.boxCondition),
    }]
    param.boxInfo.packingFileList = JSON.parse(resp.packingFileList) || []
  })

  param.dialogVisibleInfo = true;
};


//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{value: 5, label: '40HQ'}, {value: 10, label: '40GP'}, {
    value: 15,
    label: '20HQ'
  }, {value: 20, label: '20GP'}]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{value: 15, label: '适货'}, {value: 10, label: '次新'}, {value: 20, label: '混提'}, {
    value: 5,
    label: '全新'
  }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const selectAll = async () => {
  checkAll.value = []
  let data = {
    pageNum: 1,
    pageSize: 10000,
  }
  await buyBoxPage(data).then(res => {
    if (res.code == "00000" && res.data.list && res.data.total) {
      debugger;
      isSelectAll.value = false
      disableHeaderCheckbox.value = true
      res.data.list.forEach(item => {
        checkAll.value.push(item)
      })
      isAllCheck.value = true
      allId.value = checkAll.value
      tableRef.value.checkAll()
    } else {
      ElMessage.error("全选失败，请刷新页面，或者手动选择")
    }
  })
}
const deselectAll = () => {
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
}
// 导出提箱单
const toExportListData = () => {
  let checkAllItem = []
  if (isSelectAll.value) {
    checkAllItem = tableRef.value.multipleSelection
  } else {
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的提箱单！')
  ElMessageBox.confirm('确认要导出选中的提箱单', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log("导出提箱单"+ids)
    let reqParameters = {packingListIds: ids};
    exportBuyBoxPackingList(reqParameters).then((res: any) => {
      downloadFileExcel(res, '提箱单信息')
    }).catch((error:any) => {
      ElMessage.error(error)
    })
  }).catch(() => {
  });
}


</script>

<style lang="scss" scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}

.elRow-box {
  font-size: 16px;

  span {
    margin-right: 5px;
  }

  span:first-child {
    font-weight: 500;
  }
}

</style>
